import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type {
  AsyncThunk,
  ActionReducerMapBuilder,
  PayloadAction,
  Slice,
} from "@reduxjs/toolkit";
import { getList, type GetListParams } from "./totalNewsAPI";
import { DataType } from "@/pages/TotalNews/Table";
import { TZ } from "@/utils/env";
import dayjs from "@/utils/dayjs";
import { v4 } from "uuid";

const threeDaysAgoStart = dayjs().tz(TZ).subtract(3, "day").unix();
const todayEnd = dayjs().tz(TZ).unix();

interface InitialState {
  params: GetListParams;
  table: {
    status: "init" | "loading" | "success" | "error";
    data: Res | undefined;
    params?: GetListParams;
  };
}

const initialState: InitialState = {
  params: {
    page: 1,
    page_size: 10,
    start_t: threeDaysAgoStart,
    end_t: todayEnd,
    channel: "",
    network: "",
    country: "",
  },
  table: {
    status: "init",
    data: undefined,
  },
};

type Res = {
  data: {
    total: number;
    page: number;
    page_data: DataType[];
  };
};
type AsyncRes = {
  data: Res;
  params: GetListParams;
};
export const getListAsync: AsyncThunk<AsyncRes, GetListParams, {}> =
  createAsyncThunk<AsyncRes, GetListParams, {}>(
    "totalNews/getListAsync",
    async (params) => {
      const res: Res = await getList(params);
      return {
        data: res,
        params,
      };
    }
  );
const tableStatus: (builder: ActionReducerMapBuilder<InitialState>) => void = (
  builder: ActionReducerMapBuilder<InitialState>
): void => {
  builder
    .addCase(getListAsync.pending, (state: InitialState): void => {
      state.table.status = "loading";
    })
    .addCase(
      getListAsync.fulfilled,
      (state: InitialState, action: PayloadAction<AsyncRes>): void => {
        state.table.status = "success";
        if (Array.isArray(action.payload?.data?.data?.page_data)) {
          action.payload.data.data.page_data.forEach((i) => (i.uuid = v4()));
        }
        state.table.data = action.payload.data;
        state.table.params = action.payload.params;
      }
    )
    .addCase(getListAsync.rejected, (state: InitialState): void => {
      state.table.status = "error";
    });
};

type Reducers = {
  changeParams: (
    state: InitialState,
    action: PayloadAction<Partial<GetListParams>>
  ) => void;
};
type Selectors = {};
const totalNewsSlice: Slice<
  InitialState,
  Reducers,
  "totalNews",
  "totalNews",
  Selectors
> = createSlice<InitialState, Reducers, "totalNews", Selectors, "totalNews">({
  name: "totalNews",
  initialState,
  reducers: {
    changeParams(
      state: InitialState,
      action: PayloadAction<Partial<GetListParams>>
    ): void {
      state.params = {
        ...state.params,
        ...action.payload,
      };
    },
  },
  extraReducers(builder: ActionReducerMapBuilder<InitialState>): void {
    tableStatus(builder);
  },
});

export const { changeParams }: typeof totalNewsSlice.actions =
  totalNewsSlice.actions;

export default totalNewsSlice.reducer;
